package com.cloudhopper.smpp.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LongMessageUtil {

	private static final Logger logger = LoggerFactory.getLogger(LongMessageUtil.class);

	/**
	 * 拆分长短信
	 * 
	 * @param content
	 *            短信内容
	 * @param charset
	 *            字符集编码
	 * @param normalSMMaxLength
	 *            短信最大长度
	 * @param headerBit
	 *            头
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static List<byte[]> splitLongMessage(String content, String charset, int normalSMMaxLength, int headerBit) throws UnsupportedEncodingException {
		if ((6 != headerBit) && (7 != headerBit)) {// headerBit为6
			throw new IllegalArgumentException("Short Message Header bit is not 6 or 7");
		}

		List<byte[]> smsList = new ArrayList<byte[]>();
		byte[] msgContent = content.getBytes(charset);// 短信内容字节码
		if (msgContent.length > normalSMMaxLength) {// 短信字节码最长254
			// 大于normalSMSLength位就要转化成长短信
			// normalSMSLength字节去掉headerBit位消息头
			int subContentlength = (normalSMMaxLength - headerBit) / " ".getBytes(charset).length;
			int smsCount;
			if ((content.length() % (subContentlength)) == 0) {
				smsCount = content.length() / (subContentlength);
			} else {
				smsCount = (content.length() / (subContentlength)) + 1;
			}
			int random = getRandom();

			String messagePross = content;
			byte[] msgBody;
			byte[] sHead;
			byte[] msgContentByteSub;
			for (int i = smsCount; i > 0; i--) {
				// 从后向前的顺序添加各分段消息
				String msgContentStrSub = messagePross.substring((i - 1) * subContentlength);
				msgBody = msgContentStrSub.getBytes(charset);
				if (6 == headerBit) {// 6 Bit
					sHead = new byte[] { 5, 0, 3, (byte) random, (byte) smsCount, (byte) (i) };
				} else {
					// 7 Bit
					sHead = new byte[] { 6, 8, 4, 0, (byte) random, (byte) smsCount, (byte) (i) };
				}

				msgContentByteSub = new byte[sHead.length + msgBody.length];

				System.arraycopy(sHead, 0, msgContentByteSub, 0, headerBit);// 拷贝6个字节
				System.arraycopy(msgBody, 0, msgContentByteSub, headerBit, msgBody.length);// 把headerBit和msgbody的字节码拼装在msgContentByteSub的字节数组中

				smsList.add(msgContentByteSub);

				if (i > 1) {
					messagePross = messagePross.substring(0, (i - 1) * subContentlength);
				}
			}

			Collections.reverse(smsList);
		} else {
			throw new IllegalArgumentException("This message is a normal SMS, the content length is " + msgContent.length);
		}

		return smsList;
	}

	/**
	 * 生成随机数，从1到255，一般取值应该大于2
	 * 
	 * @return
	 */
	public static int getRandom() {
		Random randomObj = new Random();
		int random = randomObj.nextInt(255);
		if (0 == random) {
			random += 2;
		} else if (1 == random) {
			random++;
		}

		return random;
	}

}
